/*
 * @Author:Iyoole
 * @Time  :2017-11-20
 * @Description:表单
 * @git:
 * */

;!function(e) {
    "use strict";
    var i,c;

    var Form=function(elem){
        this.elem=elem?i(elem):i('body');
        c={
            code:0,
            msg:"",
            result:""
        };
    };
    Form.pt=Form.prototype;
    Form.pt.render=function(){
        var t=this;
        t.elem.find('[fm-radio]').each(function(){
            var _t=i(this),rn=_t.attr('fm-radio'),rv=_t.val();
            t.elem.find('[fm-name="'+rn+'"][fm-value="'+rv+'"]').addClass('fui-radio-checked');
        });
        t.elem.find('[fm-checkbox]').each(function(){
            var _t=i(this),rn=_t.attr('fm-checkbox'),rv=_t.val();
            if(rv=="") return;
            rv=rv.split(',');
            i.each(rv,function(m,n){
                t.elem.find('[name="'+rn+'"][value="'+n+'"]').prop('checked',true).parent().addClass('fui-checkbox-checked');
            })
        });
        t.elem.find('.form-item-switch').each(function(){
            var _t=i(this),ipt=_t.find('input'),ts=_t.attr('fm-switch').split('|'),tv=_t.attr('fm-value').split('|'),tp=_t.find('span');
            ipt.val()==tv[0]?tp.text(ts[0]):(tp.text(ts[1]),_t.addClass('fui-switch-checked'));
        });
        t.elem.find('[fm-select]').each(function(){
            var _t=i(this),ta=_t.parent('.form-item-select'),ipt=ta.find('.form-select-title input'),list=ta.find('.form-select-option'),tv=_t.val();
            if(tv=='') return;
            var poll=function(m,v,type){
                if(m>10){return}
                if(list.find('[fm-value="'+v+'"]').length==0){
                    m++;
                    setTimeout(function(){poll(m,v,type)},300)
                }else{
                    list.find('[fm-value="'+v+'"]').addClass('checked');
                    if(type==1){
                        ipt.val(list.find('[fm-value="'+v+'"]').text())
                    }
                }
            };
            if(list.hasClass('form-select-multiple')){
                var nv=tv.split(',');
                i.each(nv,function(x,y){
                    poll(0,y)
                });
            }else{
                poll(0,tv,1);
            }
        });
    };
    Form.pt.submit=function(f,obj){
        var t=this,flag=false,na="";
        i.each(t.elem.find('[fm-verify]'),function(m,n){
            var _t=i(n),v=_t.attr('fm-verify'),_v=_t.val();
            na=_t.data('name')||"";
            if(!!v){
                v=v.split('|');
                i.each(v,function(x,y){
                    if(t[y]&&!t[y].call(t,_v)){
                        flag=true;
                        return false
                    }else{
                        if(y=='url'&&_v!=''){
                            _t.val(t.http(_t.val()));
                        }
                    }
                });
                if(flag) return false;
            }
        });
        i.each(t.elem.find('[fm-checkbox]'),function(m,n){
            var _t=i(n),v=_t.attr('fm-checkbox');
            if(v=='required'){
                if(_t.find('.fui-checkbox-checked').length==0){
                    na=_t.data('name')||'';
                    flag=true;
                    c.msg='请勾选';
                    return false
                }
            }
        });

        if(!flag){
            c.code=1;
            !obj?t.serialize():t.json();
        }
        var nj={code:c.code,msg:na+c.msg,result:c.result};
        f(nj)
    };
    Form.pt.serialize=function(){
        var t=this;
        c.result=t.elem.serialize()
    };
    Form.pt.json=function(){
        var t=this,jn={},cn=[],cj={};
        i.each(t.elem.find('[type="text"][name]'),function(m,n){
            var _t=i(n);
            jn[_t.attr('name')]=_t.val();
        });
        i.each(t.elem.find('[type="hidden"][name]'),function(m,n){
            var _t=i(n);
            jn[_t.attr('name')]=_t.val();
        });
        i.each(t.elem.find('[type="password"][name]'),function(m,n){
            var _t=i(n);
            jn[_t.attr('name')]=_t.val();
        });
        i.each(t.elem.find('[type="radio"]:checked'),function(x,y){
            var _t=i(y),tn=_t.attr('name');
            !!tn?jn[tn]=_t.val():"";
        });
        i.each(t.elem.find('[type="checkbox"]:checked'),function(x,y){
            var _t=i(y),tn=_t.attr('name');
            if(i.inArray(tn,cn)==-1){
                cn.push(tn);
                cj[tn]=[];
            }
            cj[tn].push(_t.val());
        });
        i.each(cn,function(k,l){
            jn[l]=cj[l].toString();
        });
        i.each(t.elem.find('select'),function(x,y){
            var _t=i(y),tn=_t.attr('name');
            jn[tn]=_t.val()
        });
        i.each(t.elem.find('textarea'),function(x,y){
            var _t=i(y),tn=_t.attr('name');
            if(tn){
                jn[tn]=_t.val()
            }
        });
        c.result=jn;
    };
    Form.pt.required=function(v){
        var _v=v.replace(/\s/g,'');
        !!_v?"":c.msg="不能为空";
        return !!_v
    };
    Form.pt.email=function(v){
        if(v=="") return true;
        var _v=/^(?:[\w-]+\.?)*[\w-]+@(?:[\w-]+\.)+[\w]{2,3}$/.test(v);
        _v?"":c.msg="格式不正确";
        return _v
    };
    Form.pt.phone=function(v){
        if(v=="") return true;
        var _v=/^1[34578]\d{9}$/.test(v);
        c?c.msg=_v?'':'格式不正确':'';
        return _v
    };
    Form.pt.tel=function(v){
        if(v=="") return true;
        var _v=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/.test(v);
        _v?"":c.msg="格式不正确";
        return _v
    };
    Form.pt.number=function(v){
        if(v=="") return true;
        var _v=/^\d+$/.test(v);
        _v?"":c.msg="必须全为数字";
        return _v
    };
    Form.pt.string=function(v){
        if(v=="") return true;
        var _v=/^[A-Za-z]+$/.test(v);
        _v?"":c.msg="必须全为字母";
        return _v
    };
    Form.pt.fax=function(v){
        if(v=="") return true;
        var _v=/^(\d{3,4}-)?\d{7,8}$/.test(v);
        _v?"":c.msg="格式不正确";
        return _v
    };
    Form.pt.idCard=function(v){
        if(v=="") return true;
        var C15ToC18 = function(c15) {
            var cId=c15.substring(0,6)+"19"+c15.substring(6,15);
            var jy  =[  "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
            var iq =[7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            var it=0;
            for(i = 0; i < cId.length ; i++)
                it +=  cId.substring(i, i + 1)  * iq[i];
            it %= 11;
            cId+=jy[it];
            return cId;
        };
        var Is18IDCard = function(IDNum) {
            var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
            var iSum=0,sID=IDNum;
            if(!/^\d{17}(\d|x)$/i.test(sID)) {
                return false;
            }
            sID=sID.replace(/x$/i,"a");
            if(aCity[parseInt(sID.substr(0,2))]==null) {
                return false;
            }
            var sBirthday=sID.substr(6,4)+"-"+Number(sID.substr(10,2))+"-"+Number(sID.substr(12,2));
            var d=new Date(sBirthday.replace(/-/g,"/"));
            if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return false;
            for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sID.charAt(17 - i),11)
            if(iSum%11!=1)return false;
            return true;
        };
        var _v=v.length==15 ? Is18IDCard(C15ToC18(v)) : Is18IDCard(v);
        _v?"":c.msg="格式不正确";
        return _v
    };
    Form.pt.ip=function(v){
        if(v=="") return true;
        var _v=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(v);
        c?c.msg=_v?'':'格式不正确':'';
        return _v
    };
    Form.pt.url=function(v){
        if(v=="") return true;
        var http=/^(https?|ftp|file):\/\//;
        v=!http.test(v)?('http://'+v):v;
        var _v=/^(https?|ftp|files):\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(v);
        c?c.msg=_v?'':'格式不正确':'';
        return _v
    };
    Form.pt.YM=function(v){
        if(v=="") return true;
        var _v=/[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/.test(v);
        c?c.msg=_v?'':'格式不正确':'';
        return _v
    };
    Form.pt.http=function(v){
        if(v=="") return true;
        var http=/^(https?|ftp|file):\/\//;
        if(!http.test(v)){
            v='http://'+v
        }
        return v;
    };
    Form.pt.skin=function(){
        var body=i('body');
        body.on('click','.form-item-radio',function(){
            var _t=i(this),tn=_t.attr('fm-name'),tv=_t.attr('fm-value');
            _t.addClass('fui-radio-checked').siblings().removeClass('fui-radio-checked');
            i('[name="'+tn+'"]').val(tv);
        });
        body.on('click','.form-item-checkbox',function(){
            var _t=i(this),tb=_t.find('[type="checkbox"]'),tp=_t.parent(),tpb=tp.find('[type="checkbox"]');
            if(tp.find('.checkboxAll').length==1){
                if(_t.hasClass('checkboxAll')){
                    if(_t.hasClass('fui-checkbox-checked')){
                        _t.removeClass('fui-checkbox-checked').siblings().removeClass('fui-checkbox-checked');
                        tpb.prop('checked',false)
                    }else{
                        _t.addClass('fui-checkbox-checked').siblings().addClass('fui-checkbox-checked');
                        tpb.prop('checked',true)
                    }
                }else{
                    if(_t.hasClass('fui-checkbox-checked')){
                        tp.find('.checkboxAll').removeClass('fui-checkbox-checked');
                        _t.removeClass('fui-checkbox-checked');
                        tb.prop('checked',false);
                    }else{
                        _t.addClass('fui-checkbox-checked');
                        tb.prop('checked',true);
                        if(tp.find('.fui-checkbox-checked').length==(tp.find('.form-item-checkbox').length-1)){
                            tp.find('.checkboxAll').addClass('fui-checkbox-checked').find('[type="checkbox"]').prop('checked',true);
                        }
                    }
                }
            }else if(tp.hasClass('form-checkbox-one')){
                if(_t.hasClass('fui-checkbox-checked')){
                    _t.removeClass('fui-checkbox-checked');
                    tb.prop('checked',false)
                }else{
                    _t.addClass('fui-checkbox-checked').siblings().removeClass('fui-checkbox-checked');
                    tpb.prop('checked',false);
                    tb.prop('checked',true)
                }
            }else{
                if(_t.hasClass('fui-checkbox-checked')){
                    _t.removeClass('fui-checkbox-checked');
                    tb.prop('checked',false)
                }else{
                    _t.addClass('fui-checkbox-checked');
                    tb.prop('checked',true)
                }
            }
            tp.find('[data-click="checkbox"]').trigger('click')
        });
        body.on('click','.form-item-switch',function(){
            var _t=i(this),ts=_t.find('span'),tp=_t.find('input'),tn=_t.attr('fm-switch').split('|'),tv=_t.attr('fm-value').split('|');
            if(_t.hasClass('fui-switch-checked')){
                _t.removeClass('fui-switch-checked');
                tp.val(tv[0]);
                ts.text(tn[0])
            }else{
                _t.addClass('fui-switch-checked');
                tp.val(tv[1]);
                ts.text(tn[1])
            }
        });

        var TITLE='form-select-title';
        var hide=function(e,clear,mul){
            if(mul){
                e.stopPropagation();
            }else{
                if(!i(e.target).parent().hasClass(TITLE)||clear){
                    body.find('.form-item-select').removeClass('fui-select-checked')
                }
            }
        };

        body.on('click','.form-item-select .form-select-title',function(){
            var _t=i(this),select=_t.parent('.form-item-select');
            select.hasClass('fui-select-checked')?select.removeClass('fui-select-checked'):(hide(e,true),select.addClass('fui-select-checked'))
        });
        body.on('click','.form-select-option li',function(e){
            var _t=i(this),ta=_t.parent(),tv=_t.attr('fm-value'),tn=ta.attr('fm-name'),mul=ta.hasClass('form-select-multiple');
            var select=_t.parents('.form-item-select'),input=select.find('.form-select-title input');
            if(_t.hasClass('noSelect')) return;
            if(mul){
                var nn=[],nv=[];
                if(_t.hasClass('checked')){
                    _t.removeClass('checked');
                }else{
                    _t.addClass('checked');
                }
                i.each(select.find('.checked'),function(x,y){
                    nn.push(i(y).text());
                    nv.push(i(y).attr('fm-value'));
                });
                input.val(nn.join(','));
                select.find('[name="'+tn+'"]').val(nv.join(','));
                hide(e,true,true)
            }else{
                if(_t.hasClass('checked')) return;
                _t.addClass('checked').siblings().removeClass('checked');
                input.val(_t.text());
                select.find('[name="'+tn+'"]').val(tv)
            }
            select.find('[name="'+tn+'"]').trigger('change')
        });
        i(document).off("click",hide).on('click',hide);
    };


    var JsForm=function(elem){
        return new Form(elem)
    };
    JsForm.v='1.0.7';
    if(window.fui && fui.define ){
        fui.define('jquery', function(exports){
            e.JsForm=JsForm;
            i=fui.$;
            exports('JsForm', JsForm);
        });
    }else{//如果直接引用的话
        e.JsForm=JsForm;
        i=e.jQuery;
    }
}(window);

/*
* 提供表单元素的基本验证
* JsForm(表单).submit(function(r){
*       r={
*           code:0/1 ---1 表示验证成功 0表示验证失败
*           msg:'' ----  验证失败的提示内容
*           result ----  验证成功以后的返回值
*       }
* },json)
* 默认json不加,是表单序列化的值
*
* required   ---  必填选项
* phone      ---  手机号
* email      ---  邮箱
* tel        ---  电话号码
* number     ---  数字
* string     ---  字母
* idCard     ---  身份证
* */
/*
* 1.0.2
* 增加复选必选功能
* 1.0.3
* 增加域名,IP,url等验证
* 1.0.4
* 取消数据返回转json字符串
* 1.0.5
* 修改下拉填充数据点击无效问题
* 1.0.6
* 优化下拉事件(添加不可选中,多选)
* 1.0.7
* 修复动态加载表单点击事件无效问题
* */






